﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace FileMerge.Helpers
{
    /// <summary>
    /// 模版帮助
    /// </summary>
    public static class TemplateHelper
    {
        /// <summary>
        /// 模版字典
        /// </summary>
        public static Dictionary<string, Func<string, string>> TemplateMapping = new Dictionary<string, Func<string, string>>();

        /// <summary>
        /// 解析模版
        /// </summary>
        /// <param name="text">模版字符串</param>
        /// <param name="fileInfo">文件信息</param>
        /// <param name="num">序号</param>
        /// <returns></returns>
        public static string Parse(string text, FileInfo fileInfo = null, int num = 0)
        {
            if (text == null || string.IsNullOrEmpty(text))
                return text;

            TemplateMapping["{{DateTime}}"] = p => DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            TemplateMapping["{{Date}}"] = p => DateTime.Now.ToString("yyyy-MM-dd");
            TemplateMapping[@"{{DateTime\((.*?)\)}}"] = p => DateTime.Now.ToString(p);

            TemplateMapping["{{FileName}}"] = p => fileInfo?.Name ?? string.Empty;
            TemplateMapping["{{FileFullName}}"] = p => fileInfo?.FullName ?? string.Empty;
            TemplateMapping["{{FileCreationtime}}"] = p => fileInfo?.CreationTime.ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty;
            TemplateMapping["{{FileLastWriteTime}}"] = p => fileInfo?.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty;
            TemplateMapping["{{FileDirectory}}"] = p => fileInfo?.DirectoryName ?? string.Empty;
            TemplateMapping[@"{{FileCreationtime\((.*?)\)}}"] = p => fileInfo?.CreationTime.ToString(p) ?? string.Empty;
            TemplateMapping[@"{{FileLastWriteTime\((.*?)\)}}"] = p => fileInfo?.LastWriteTime.ToString(p) ?? string.Empty;
            TemplateMapping[@"{{FileInfo\((.*?)\)}}"] = p => FileInfoHelper.GetFileProperty(fileInfo.FullName, p).Value ?? string.Empty;

            TemplateMapping["{{Num}}"] = p => num.ToString();
            TemplateMapping[@"{{Num\((\w*?)\)}}"] = p => num.ToString(p);

            foreach (var pair in TemplateMapping)
            {
                while (true)
                {
                    var match = Regex.Match(text, pair.Key);

                    if (!match.Success) break;

                    var format = match.Groups.Count > 1 ? match.Groups[1].Value : string.Empty;

                    try
                    {
                        text = text.Remove(match.Index, match.Length);
                        text = text.Insert(match.Index, pair.Value(format));
                    }
                    catch { continue; }
                }
            }

            return text;
        }
    }
}
